window.onload = function () {
    loadStudent()
    loadGrade()
}

// 加载年级信息
function loadGrade() {
    let xhr = new XMLHttpRequest()
    /* 
        https://www.bingjs.com:8001/Grade/GetAll  查询全部年级信息  [GET请求]
    */
    xhr.open("GET", `https://www.bingjs.com:8001/Grade/GetAll`)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            let str = JSON.parse(xhr.response)
            str.unshift({ GradeId: 0, GradeName: "请选择年级" })
            console.log(str)
            str.forEach(a => {
                let option = document.createElement("option")
                console.log(option);
                option.value = a.GradeId
                option.innerHTML = a.GradeName
                gradeId.appendChild(option)
            })
        }
    }
}

// 加载学生信息的方法
function loadStudent() {
    // 发送Ajax请求获取学生信息
    let xhr = new XMLHttpRequest()
    // 清空之前的数据
    tbody.innerHTML = ""

    // 获取搜索框里的内容
    let studentName = searchText.value
    // 获取所有的性别单选框
    let sexes = document.getElementsByName("sex")
    // 定义性别
    let sex = ""
    sexes.forEach(r => {
        if (r.checked) {
            sex = r.value
        }
    })
    /* 
        https://www.bingjs.com:8001/Student/GetStudentsConditionPages  查询学生+条件+分页    [GET请求]
        (参数studentName：学生姓名，可以为空，支持模糊查询)
        (参数sex：学生性别，可以为空，M表示男，F表示女)
        (参数pageIndex：页码，默认值是1)
        (参数pageSize：每页数量，默认值是10)
    */
    xhr.open("GET", `https://www.bingjs.com:8001/Student/GetStudentsConditionPages?pageIndex=${pageIndex.innerHTML}&studentName=${studentName}&sex=${sex}`)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 获取数据 总数量 当前页码 每页数量
            let { data, count, pageIndex, pageSize } = JSON.parse(xhr.response)
            console.log(data);
            // 总页数
            let pageCount = Math.ceil(count / pageSize)
            // 显示总页数
            totalPage.innerHTML = pageCount
            data.forEach(a => {
                console.log(a);
                let tr = document.createElement("tr")
                let td_studentNo = document.createElement("td")
                td_studentNo.innerHTML = a.StudentNo
                let td_loginPwd = document.createElement("td")
                td_loginPwd.innerHTML = a.LoginPwd
                let td_studentName = document.createElement("td")
                td_studentName.innerHTML = a.StudentName
                let td_studentSex = document.createElement("td")
                td_studentSex.innerHTML = a.Sex === "M" ? "男" : "女"
                let td_studentGrade = document.createElement("td")
                td_studentGrade.innerHTML = a.Grade.GradeName
                let td_studentPhone = document.createElement("td")
                td_studentPhone.innerHTML = a.Phone
                let td_studentAddress = document.createElement("td")
                td_studentAddress.innerHTML = a.Address
                let td_studentBorn = document.createElement("td")
                td_studentBorn.innerHTML = a.BornDate
                td_studentBorn.innerHTML = bornDate(new Date(a.BornDate))
                let td_studentEmail = document.createElement("td")
                td_studentEmail.innerHTML = a.Email
                let td_studentIdentityCard = document.createElement("td")
                td_studentIdentityCard.innerHTML = a.IdentityCard
                let td_action = document.createElement("td")
                let btn_modify = document.createElement("button")
                btn_modify.innerHTML = "修改"
                let btn_del = document.createElement("button")
                btn_del.innerHTML = "删除"

                td_action.appendChild(btn_modify)
                td_action.appendChild(btn_del)
                tr.appendChild(td_studentNo)
                tr.appendChild(td_loginPwd)
                tr.appendChild(td_studentName)
                tr.appendChild(td_studentSex)
                tr.appendChild(td_studentGrade)
                tr.appendChild(td_studentPhone)
                tr.appendChild(td_studentAddress)
                tr.appendChild(td_studentBorn)
                tr.appendChild(td_studentEmail)
                tr.appendChild(td_studentIdentityCard)
                tr.appendChild(td_action)
                tbody.appendChild(tr)

                // 修改学生信息
                let btn_modify_tr = document.getElementsByTagName("tbody")[0].children
                console.log(btn_modify_tr);
                let btn_modify_td = btn_modify_tr[0].children
                console.log(btn_modify_td[10].firstElementChild);
                console.log((btn_modify_tr[0].children[10].firstElementChild));
                for (let i = 0; i < btn_modify_tr.length; i++) {
                    btn_modify_tr[i].children[10].firstElementChild.onclick = function () {
                        let modify_box = document.getElementsByClassName("modify_box")[0]
                        modify_box.style.display = "block"
                        let modify_tbody_tr = document.getElementById("modify_tbody").children
                        console.log(modify_tbody_tr);
                        let modify_studentNo = modify_tbody_tr[0].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_studentNo);
                        modify_studentNo.value = btn_modify_tr[i].firstElementChild.innerHTML

                        let modify_loginPwd = modify_tbody_tr[1].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_loginPwd);
                        modify_loginPwd.value = btn_modify_tr[i].firstElementChild.nextElementSibling.innerHTML

                        let modify_studentName = modify_tbody_tr[2].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_studentName);
                        modify_studentName.value = btn_modify_tr[i].firstElementChild.nextElementSibling.nextElementSibling.innerHTML

                        let modify_sex = modify_tbody_tr[3].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_sex);
                        modify_sex.value = btn_modify_tr[i].firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML
                        console.log(modify_sex.value);
                        if(modify_sex.value === "男"){
                            document.getElementsByName('sex')[3].checked = true
                        }else{
                            document.getElementsByName('sex')[4].checked = true
                        }
                        let modify_gradeId = modify_tbody_tr[4].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_gradeId);
                        modify_gradeId.selected = btn_modify_tr[i].firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML
                        console.log(modify_gradeId.selected);
                        console.log(document.getElementsByTagName("option")[1])
                        if(modify_gradeId.selected === "S1"){
                            document.getElementsByTagName("option")[1].selected = true
                        }else if(modify_gradeId.selected === "S2"){
                            document.getElementsByTagName("option")[2].selected = true
                        }else if(modify_gradeId.selected === "Y2"){
                            document.getElementsByTagName("option")[3].selected = true
                        }
                        let modify_phone = modify_tbody_tr[5].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_phone);
                        modify_phone.value = btn_modify_tr[i].firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML
                        console.log(modify_phone.value);

                        let modify_address = modify_tbody_tr[6].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_address);
                        modify_address.value = btn_modify_tr[i].firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML

                        let modify_bornDate = modify_tbody_tr[7].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_bornDate);
                        modify_bornDate.value = btn_modify_tr[i].firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML

                        let modify_email = modify_tbody_tr[8].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_email);
                        modify_email.value = btn_modify_tr[i].firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML

                        let modify_identityCard = modify_tbody_tr[9].firstElementChild.nextElementSibling.firstElementChild
                        console.log(modify_identityCard);
                        modify_identityCard.value = btn_modify_tr[i].firstElementChild.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML

                        // 修改按钮点击事件
                        let modify_btn = document.getElementById("modify_student_submit")
                        console.log(modify_btn);
                        modify_btn.onclick = function () {
                            let studentNo = modify_tbody_tr[0].firstElementChild.nextElementSibling.firstElementChild.value
                            let loginPwd = modify_tbody_tr[1].firstElementChild.nextElementSibling.firstElementChild.value
                            let studentName = modify_tbody_tr[2].firstElementChild.nextElementSibling.firstElementChild.value
                            let sex = [...document.getElementsByName("sex")].find(a => a.checked).value
                            console.log(sex);
                            // let gradeId = modify_tbody_tr[4].firstElementChild.nextElementSibling.firstElementChild.selected
                            let gradeId = [...document.getElementsByTagName("option")].find(a => a.selected).value
                            let phone = modify_tbody_tr[5].firstElementChild.nextElementSibling.firstElementChild.value
                            let address = modify_tbody_tr[6].firstElementChild.nextElementSibling.firstElementChild.value
                            let bornDate = modify_tbody_tr[7].firstElementChild.nextElementSibling.firstElementChild.value
                            let email = modify_tbody_tr[8].firstElementChild.nextElementSibling.firstElementChild.value
                            let identityCard = modify_tbody_tr[9].firstElementChild.nextElementSibling.firstElementChild.value
                            let modify_obj = {
                                studentNo,
                                loginPwd,
                                studentName,
                                sex,
                                gradeId,
                                phone,
                                address,
                                bornDate,
                                email,
                                identityCard
                            }
                            let modify_json = JSON.stringify(modify_obj)
                            let xhr = new XMLHttpRequest()
                            /* 
                                https://www.bingjs.com:8001/Student/Update  修改学生    [POST请求]
                                参数：
                                (
                                    studentNo 学号，
                                    loginPwd 密码，
                                    studentName 姓名，
                                    sex 性别，
                                    gradeId 年级编号，
                                    phone 电话，
                                    address 地址，
                                    bornDate 生日，
                                    email 邮箱，
                                    identityCard 身份证
                                )
                            */
                            xhr.open("POST", `https://www.bingjs.com:8001/Student/Update`)
                            xhr.setRequestHeader("Content-Type", "application/json")
                            xhr.send(modify_json)
                            xhr.onreadystatechange = function () {
                                if (xhr.readyState === 4 && xhr.status === 200) {
                                    let modify_obj = JSON.parse(xhr.response)
                                    console.log(modify_obj);
                                    if (modify_obj) {
                                        loadStudent()
                                        alert("操作成功")
                                    }
                                }
                            }
                        }
                        // 取消按钮点击事件
                        let modify_btn_cancel_btn = document.getElementById("modify_student_cancel")
                        modify_btn_cancel_btn.onclick = function () {
                            modify_box.style.display = "none"
                        }
                    }

                }
                // 删除学生信息
                btn_del.onclick = function () {
                    if (!confirm(`你确定要删除${a.StudentNo}${a.StudentName}嘛`)) {
                        return
                    }
                    // 通过Ajax 获取数据 并删除
                    let xhr = new XMLHttpRequest()
                    xhr.open("POST", " https://www.bingjs.com:8001/Student/Delete")
                    // 删除数据 studentNo
                    // ajax 请求报 415 ，请求参数类型与后台接收参数未对应
                    // 解决方式：添加contentType，同时将data参数转为json字符串即可
                    // xhr.setRequestHeader ("content-type", "application/x-www-form-urlencoded" )
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
                    xhr.send("studentNo=" + a.StudentNo)
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            let obj = JSON.parse(xhr.response)
                            if (obj) {
                                alert("删除成功")
                                location.href = "../html/searchStudent.html"
                            }
                        }
                    }
                }
            })
        }
    }
}


//修改日期格式
function bornDate(data) {
    let year = data.getFullYear()
    let month = data.getMonth() + 1
    let day = data.getDate()
    // console.log(year, month, day);
    return [year, month, day].map(a => pacth0(a)).join("-")

}

// 补0操作 如果是单数就添加一个0
function pacth0(val) {
    return (val + "").length > 1 ? val : "0" + val
}

// 首页按钮点击事件
first.onclick = function () {
    // 将页码设置为1
    if (pageIndex.innerHTML == 1) {
        return
    }
    pageIndex.innerHTML = 1
    // 调用加载学生信息的方法
    loadStudent()
}

// 下一页按钮点击事件
next.onclick = function () {
    // 获取当前页数
    let index = parseInt(pageIndex.innerHTML)
    // 获取总页数
    let indexCount = parseInt(totalPage.innerHTML)
    // 如果当前页小于总页数
    if (index < indexCount) {
        index++
        pageIndex.innerHTML = index
        loadStudent()
    }
}

// 上一页按钮点击事件
prev.onclick = function () {
    // 获取当前页数
    let index = parseInt(pageIndex.innerHTML)
    // 如果当前页数大于1
    if (index > 1) {
        index--
        pageIndex.innerHTML = index
        loadStudent()
    }
}

// 尾页按钮点击事件
last.onclick = function () {
    // 获取当前页数
    let index = parseInt(pageIndex.innerHTML)
    // 获取总页数
    let indexCount = parseInt(totalPage.innerHTML)
    // 当前页码设置为总页码
    if (index != indexCount) {
        pageIndex.innerHTML = totalPage.innerHTML
        loadStudent()
    }

}

// 搜索按钮点击事件
searchBtn.onclick = function () {
    // 调用加载学生信息
    loadStudent()
}



// 根据学号查询单个学生信息
// 查询按钮点击事件
searchByNoBtn.onclick = function () {
    // 发送Ajax请求获取学生信息
    let xhr = new XMLHttpRequest()
    // 清空之前的数据
    searchByNo_tbody.innerHTML = ""
    // 获取搜索框里的内容
    let studentNo = searchTextByNo.value
    if (studentNo === "") {
        alert("学号不可以为空！请输入学号！")
    }
    /* 
          https://www.bingjs.com:8001/Student/GetStudentByNo  根据学号查询单个学生信息    [GET请求]
          (参数studentNo：学生学号，不可以为空) 
    */
    xhr.open("GET", `https://www.bingjs.com:8001/Student/GetStudentByNo?StudentNo=${studentNo}`)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            let str = JSON.parse(xhr.response)
            console.log(str);
            let c_tr = document.createElement("tr")
            let c_td_studentNo = document.createElement("td")
            c_td_studentNo.innerHTML = str.StudentNo
            let c_td_loginPwd = document.createElement("td")
            c_td_loginPwd.innerHTML = str.LoginPwd
            let c_td_studentName = document.createElement("td")
            c_td_studentName.innerHTML = str.StudentName
            let c_td_studentSex = document.createElement("td")
            c_td_studentSex.innerHTML = str.Sex === "M" ? "男" : "女"
            let c_td_studentGrade = document.createElement("td")
            c_td_studentGrade.innerHTML = str.Grade.GradeName
            let c_td_studentPhone = document.createElement("td")
            c_td_studentPhone.innerHTML = str.Phone
            let c_td_studentAddress = document.createElement("td")
            c_td_studentAddress.innerHTML = str.Address
            let c_td_studentBorn = document.createElement("td")
            c_td_studentBorn.innerHTML = str.BornDate
            c_td_studentBorn.innerHTML = bornDate(new Date(str.BornDate))
            let c_td_studentEmail = document.createElement("td")
            c_td_studentEmail.innerHTML = str.Email
            let c_td_studentIdentityCard = document.createElement("td")
            c_td_studentIdentityCard.innerHTML = str.IdentityCard

            c_tr.appendChild(c_td_studentNo)
            c_tr.appendChild(c_td_loginPwd)
            c_tr.appendChild(c_td_studentName)
            c_tr.appendChild(c_td_studentSex)
            c_tr.appendChild(c_td_studentGrade)
            c_tr.appendChild(c_td_studentPhone)
            c_tr.appendChild(c_td_studentAddress)
            c_tr.appendChild(c_td_studentBorn)
            c_tr.appendChild(c_td_studentEmail)
            c_tr.appendChild(c_td_studentIdentityCard)
            searchByNo_tbody.appendChild(c_tr)
        }
    }
}